<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import BooksList from "@/components/BooksList.vue";
import axios from "axios";
import { useShopcartStore } from "@/stores/shopcart";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const shopcartStore = useShopcartStore();
const keyword = ref("");
const searchResults = ref([]);
const loading = ref(true);
const error = ref("");
const randomBooks = ref([]);
const loadingRandomBooks = ref(false);

// 执行搜索
const performSearch = async () => {
  if (!keyword.value) return;
  
  loading.value = true;
  error.value = "";
  
  try {
    const response = await axios.get(`/api/searchBooks?keyword=${encodeURIComponent(keyword.value)}`);
    if (response.data.code === 200) {
      searchResults.value = response.data.data;
    } else {
      error.value = response.data.message || "搜索失败，请稍后重试";
    }
  } catch (err) {
    console.error("搜索出错:", err);
    error.value = "搜索服务暂时不可用，请稍后重试";
  } finally {
    loading.value = false;
  }
};

// 获取随机书籍推荐
const getRandomBookRecommendations = async () => {
  loadingRandomBooks.value = true;
  try {
    const response = await axios.get('/api/randomBooks?count=4');
    if (response.data.code === 200) {
      randomBooks.value = response.data.data;
    }
  } catch (err) {
    console.error("获取随机书籍推荐出错:", err);
  } finally {
    loadingRandomBooks.value = false;
  }
};

// 添加到购物车
const addToCart = async (book) => {
  try {
    const result = await shopcartStore.addToCart(book.b_id, 1);
    
    if (result.success) {
      ElMessage.success("加入购物车成功");
    } else {
      ElMessage.error(result.message || "加入购物车失败");
    }
  } catch (error) {
    console.error("添加购物车出错:", error);
    ElMessage.error("添加购物车时出错，请稍后重试");
  }
};

// 前往书籍详情页
const goToBookDetail = (bookId) => {
  router.push(`/booksDetails/${bookId}`);
};

onMounted(() => {
  // 从URL参数获取搜索关键词
  keyword.value = route.query.keyword || "";
  if (keyword.value) {
    performSearch();
  } else {
    loading.value = false;
  }
  
  // 获取随机书籍推荐
  getRandomBookRecommendations();
});
</script>

<template>
  <div class="search-results-container">
    <div class="search-header">
      <h1>搜索结果: "{{ keyword }}"</h1>
      <p v-if="searchResults.length > 0" class="result-count">
        找到 {{ searchResults.length }} 个相关结果
      </p>
    </div>

    <div v-if="loading" class="loading">
      <p>正在搜索，请稍候...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
    </div>
    
    <div v-else-if="searchResults.length === 0" class="no-results">
      <p>没有找到与"{{ keyword }}"相关的书籍</p>
      <p>建议：</p>
      <ul>
        <li>请检查您的拼写</li>
        <li>尝试使用更通用的关键词</li>
        <li>尝试使用其他相关词汇</li>
      </ul>
    </div>
    
    <div v-else class="results">
      <BooksList :customBooksList="searchResults" cate="搜索" />
    </div>
    
    <!-- 随机书籍推荐 -->
    <div class="random-recommendations">
      <h2>猜你喜欢</h2>
      <div v-if="loadingRandomBooks" class="loading-recommendations">
        <p>加载推荐中...</p>
      </div>
      <div v-else class="recommendations-grid">
        <div v-for="book in randomBooks" :key="book.b_id" class="book-card">
          <div class="book-image" @click="goToBookDetail(book.b_id)">
            <img :src="book.img" :alt="book.bookname" />
          </div>
          <div class="book-info">
            <h3 class="book-title" @click="goToBookDetail(book.b_id)">{{ book.bookname }}</h3>
            <p class="book-author">{{ book.author }}</p>
            <p class="book-price">¥{{ book.price }}</p>
            <div class="book-actions">
              <a href="javascript:void(0);" class="add-to-cart" @click.prevent="addToCart(book)">加入购物车</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-results-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.search-header h1 {
  font-size: 24px;
  color: #333;
}

.result-count {
  color: #666;
  margin-top: 5px;
}

.loading, .error, .no-results {
  text-align: center;
  padding: 40px 0;
}

.loading p {
  color: #666;
}

.error p {
  color: #e60000;
}

.no-results {
  color: #666;
}

.no-results ul {
  list-style-type: disc;
  margin-left: 20px;
  text-align: left;
  max-width: 300px;
  margin: 10px auto;
}

.no-results li {
  margin: 5px 0;
}

/* 随机书籍推荐样式 */
.random-recommendations {
  margin-top: 40px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.random-recommendations h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.loading-recommendations {
  text-align: center;
  padding: 20px 0;
  color: #666;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.book-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.book-card:hover {
  transform: translateY(-5px);
}

.book-image {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-color: #f5f5f5;
  cursor: pointer;
}

.book-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.book-info {
  padding: 15px;
}

.book-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.book-title:hover {
  color: #e60000;
}

.book-author {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px;
}

.book-price {
  font-size: 16px;
  color: #e60000;
  font-weight: bold;
  margin-bottom: 10px;
}

.book-actions {
  text-align: center;
  margin-top: 10px;
}

.add-to-cart {
  display: inline-block;
  padding: 6px 15px;
  background-color: #e60000;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  text-decoration: none;
  transition: background-color 0.3s;
}

.add-to-cart:hover {
  background-color: #c00;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .recommendations-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .recommendations-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .recommendations-grid {
    grid-template-columns: 1fr;
  }
}
</style> 